<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
  <script src="../js/babel.js"></script>

  <style>
    .list {
      height: 150px;
      width: 200px;
      overflow: auto;
    }

    .li {
      height: 30px;
      background-color: skyblue;
    }
  </style>
</head>

<body>
  <div id="root"></div>
</body>

</html>

<script type="text/babel">

  // getSnapshotBeforUpdate  -> 保存快照值 在componentDidUpdate 中的第三个参数中可以接收到那个快照值
  class Snapshot extends React.Component {
    constructor(props) {
      super(props)
      this.state = { newsArr: [] }
    }

    componentDidMount() {
      this.timer = setInterval(() => {
        const news = '新闻' + (this.state.newsArr.length + 1)
        this.setState({
          newsArr: [news, ...this.state.newsArr]
        })
      }, 1000)
    }

    getSnapshotBeforeUpdate() {
      return this.refs.list.scrollHeight  // 这里的快照值保存为滚动条的高度
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
      this.refs.list.scrollTop += this.refs.list.scrollHeight - snapshot  // 用当前的滚动条的高度 - 保存的快照(过去的)滚动条的高度
    }

    render() {
      return (
        <ul className='list' ref='list'>
          {this.state.newsArr.map((item, index) => {
            return <li className='li' key={index}>{item}</li>
          })}
        </ul>
      )
    }
  }

  ReactDOM.render(<Snapshot />, document.getElementById('root'))

</script>